// pages/cart/cart.js
const app = getApp();

Page({
  data: {
    cartList: [],
    allSelected: false,
    selectedCount: 0,
    totalPrice: 0
  },

  onLoad() {
    this.loadCart();
  },

  onShow() {
    this.loadCart();
  },

  // 加载购物车
  loadCart() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      return;
    }

    app.showLoading();
    app.request({
      url: '/cart/list',
      method: 'GET',
      data: { userId: userInfo.id }
    }).then(res => {
      if (res.success) {
        const cartList = (res.data || []).map(item => ({
          ...item,
          selected: false,
          productImage: this.getFirstImage(item.productImages)
        }));
        this.setData({ cartList });
        this.calculateTotal();
      }
    }).catch(err => {
      console.error('加载购物车失败', err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  // 获取第一张图片
  getFirstImage(images) {
    if (!images) {
      return 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
    }
    const imageArray = images.split(',');
    return imageArray[0] || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
  },

  // 切换选中
  toggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    const cartList = this.data.cartList.map(item => {
      if (item.id === id) {
        item.selected = !item.selected;
      }
      return item;
    });
    this.setData({ cartList });
    this.calculateTotal();
  },

  // 全选/取消全选
  toggleSelectAll() {
    const allSelected = !this.data.allSelected;
    const cartList = this.data.cartList.map(item => {
      item.selected = allSelected;
      return item;
    });
    this.setData({ cartList, allSelected });
    this.calculateTotal();
  },

  // 计算总价
  calculateTotal() {
    let selectedCount = 0;
    let totalPrice = 0;
    
    this.data.cartList.forEach(item => {
      if (item.selected) {
        selectedCount += item.quantity;
        totalPrice += item.productPrice * item.quantity;
      }
    });

    const allSelected = this.data.cartList.length > 0 && 
                       this.data.cartList.every(item => item.selected);

    this.setData({
      selectedCount,
      totalPrice: totalPrice.toFixed(2),
      allSelected
    });
  },

  // 增加数量
  increaseQuantity(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.cartList.find(i => i.id === id);
    
    if (!item) return;

    const newQuantity = item.quantity + 1;
    app.request({
      url: `/cart/update?id=${id}&quantity=${newQuantity}`,
      method: 'PUT'
    }).then(res => {
      if (res.success) {
        this.loadCart();
      } else {
        app.showToast(res.message || '更新失败');
      }
    }).catch(err => {
      app.showToast('更新失败，请稍后重试');
      console.error('更新购物车失败', err);
    });
  },

  // 减少数量
  decreaseQuantity(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.cartList.find(i => i.id === id);
    
    if (!item || item.quantity <= 1) return;

    const newQuantity = item.quantity - 1;
    app.request({
      url: `/cart/update?id=${id}&quantity=${newQuantity}`,
      method: 'PUT'
    }).then(res => {
      if (res.success) {
        this.loadCart();
      } else {
        app.showToast(res.message || '更新失败');
      }
    }).catch(err => {
      app.showToast('更新失败，请稍后重试');
      console.error('更新购物车失败', err);
    });
  },

  // 删除商品
  deleteItem(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          const userInfo = wx.getStorageSync('userInfo');
          app.request({
            url: `/cart/delete?id=${id}&userId=${userInfo.id}`,
            method: 'DELETE'
          }).then(res => {
            if (res.success) {
              app.showToast('删除成功', 'success');
              this.loadCart();
            } else {
              app.showToast(res.message || '删除失败');
            }
          }).catch(err => {
            app.showToast('删除失败，请稍后重试');
            console.error('删除购物车商品失败', err);
          });
        }
      }
    });
  },

  // 查看商品详情
  viewProduct(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${id}`
    });
  },

  // 去逛逛
  goShopping() {
    wx.switchTab({
      url: '/pages/product-list/product-list'
    });
  },

  // 结算
  checkout() {
    if (this.data.selectedCount === 0) {
      app.showToast('请选择要结算的商品');
      return;
    }

    const selectedItems = this.data.cartList.filter(item => item.selected);
    
    // 将选中的商品信息存储到全局数据中
    getApp().globalData.checkoutItems = selectedItems;
    
    // 跳转到订单确认页面
    wx.navigateTo({
      url: '/pages/order-confirm/order-confirm'
    });
  }
});


